/**
 *All rights Reserved, Designed By Water
 */
package com.ja.util;

import java.io.*;


/**   
 * @ClassName:HttpHelper   
 * @Description:TODO
 * @author:Water 
 * @date: 2015-7-13 下午5:12:32  
 * @version V1.0  
 */
public class HttpHelper {
	
	
	/** 
     * Http Post 请求 
     * @param url 服务地址
     * @param paramContent 请求参数
     * @param charSet 编码类型
     * @param connTimeOut 连接超时时间
     * @param soTimeOut 数据读取超时时间
     * @return 服务返回内容
     * @throws Exception 
     */  
	public static String httpPost(String url, String paramContent, String charSet, int connTimeOut, int soTimeOut) {
		StringBuffer message = null;
		java.net.HttpURLConnection connection = null;
		java.net.URL reqUrl = null;
		//OutputStreamWriter reqOut = null;
		OutputStream out = null;
		InputStream in = null;
		BufferedReader br = null;
		String param = paramContent;
		String identifier = System.currentTimeMillis() + "";
		if (null == charSet || "".equals(charSet)) {
			charSet = "GBK";
		}
		try {
			message = new StringBuffer();// 创建对象接收响应信息
			reqUrl = new java.net.URL(url);
			connection = (java.net.HttpURLConnection)reqUrl.openConnection();// 创建连接
			connection.setRequestMethod("POST");
			connection.setReadTimeout(soTimeOut);// 设置读取数据超时时间
			connection.setConnectTimeout(connTimeOut);// 设置连接地址超时时间
			connection.setDoOutput(true);// 使用post方式的时候，需要使用 URL
											// 连接进行输出，所以设定为true
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

//			reqOut = new OutputStreamWriter(connection.getOutputStream(), charSet);
//			reqOut.write(param);// 将参数信息添加到输出流中
//			reqOut.flush();// 刷新该流的缓冲

			out = connection.getOutputStream();
			out.write(param.getBytes("utf-8"));
			out.flush();



			int charCount = -1;
			in = connection.getInputStream();
			br = new BufferedReader(new InputStreamReader(in, charSet));// 设定收取响应字符的编码格式
			while ((charCount = br.read()) != -1) {
				message.append((char) charCount);// 将响应信息添加到message对象中
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return "EXCEPTION";
		} finally {
			try {
				// 关闭打开的输入流和输出流
				in.close();
				out.close();
				//reqOut.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return message.toString();
	}
}
